/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dotexe.webframework.core.triggers;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;

import com.dotexe.webframework.core.ClientApplication;

/**
 *
 * @author jovan.tomasevic
 */
public class Trigger {

    private String name;
    private String methodName;
    private ClientApplication application;
    private ArrayList<MethodCongif> postEvents;

    public Trigger() {
        this.postEvents = new ArrayList<MethodCongif>();
    }

    public Trigger(ClientApplication application, String methodName) {
        this();
        this.application = application;
        this.methodName = methodName;
        this.name = methodName;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public void addOnFire(ClientApplication application, String methodName) {
        Iterator it = this.postEvents.iterator();
        while (it.hasNext()) {
            MethodCongif toRemove = (MethodCongif) it.next();
            if (toRemove.methodName.equals(methodName)) {
                it.remove();
            }
        }

        this.postEvents.add(new MethodCongif(application, methodName));
    }

    /**
     * @return the application
     */
    public ClientApplication getApplication() {
        return application;
    }

    /**
     * @param application the application to set
     */
    public void setApplication(ClientApplication application) {
        this.application = application;
    }

    /**
     * @return the methodName
     */
    public String getMethodName() {
        return methodName;
    }

    /**
     * @param methodName the methodName to set
     */
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public void fire() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        this.application.getClass().getMethod(this.methodName).invoke(this.application);
        for (int i = 0; i < this.postEvents.size(); i++) {
            ClientApplication app = this.postEvents.get(i).application;
            String method = this.postEvents.get(i).methodName;
            app.getClass().getMethod(method).invoke(app);
        }
    }

    public class MethodCongif {

        public ClientApplication application;
        public String methodName;

        public MethodCongif(ClientApplication Application, String MethodName) {
            this.application = Application;
            this.methodName = MethodName;
        }
    }
}
